<?php
 /*************************************\
 *         QDB API by Platzii          *
 *       Last update: 2012-01-14	     *
 \*************************************/

define("MYSQL_ADDR", "127.0.0.1");
define("MYSQL_PORT", 3306);
define("MYSQL_USER", "username");
define("MYSQL_PASS", "password");
define("MYSQL_DB", "database");

connect_or_die();

if (isset($_GET['quoteid']) && intval($_GET['quoteid'])) {
	$data = getdata(sprintf("SELECT * FROM qdbs_quotes WHERE id = %d", $_GET['quoteid']));

	if (empty($data)) { result_error(1, array($_GET['quoteid'])); }

	result_quoteid($data);
}
elseif (isset($_GET['numquotes'])) {
	$data = getdata("SELECT COUNT(*) FROM qdbs_quotes");

	if ($data['COUNT(*)'] <= 0) { result_error(2); }

	result_numquotes($data['COUNT(*)']);
}
elseif (isset($_GET['random'])) {
	$data = getdata("SELECT * FROM qdbs_quotes ORDER BY RAND() LIMIT 1;");

	if (empty($data)) { result_error(1, $_GET['quoteid']); }

	result_quoteid($data);
}
else {
	result_error(3);
}

function connect_or_die() {
	global $mysql_conn;

	$mysql_conn = mysql_connect(MYSQL_ADDR.':'.MYSQL_PORT, MYSQL_USER, MYSQL_PASS) or result_error(4);
	mysql_select_db(MYSQL_DB, $mysql_conn) or result_error(4);
}

function getdata($sqlquery) {	
	$result = mysql_query($sqlquery) or result_error(4);

	$data = mysql_fetch_array($result, MYSQL_ASSOC);

	return $data;
}

function result_quoteid($data)
{	
	$result = Array (
		'error' => 0,
		'errorcode' => 0,
		'errormsg' => 'No errors',
		'result' => Array (
			'id' => $data['id'],
			'quote' => utf8_encode_all($data['quote']),
			'rating' => $data['rating']
		)
	);
	send_result($result);
}

function result_numquotes($count)
{
	$result = Array (
		'error' => 0,
		'errorcode' => 0,
		'errormsg' => 'No errors.',
		'result' => Array (
			'num' => $count
		)
	);
	send_result($result);
}

function result_error($errorcode, $param = NULL)
{
	$errormsg = Array(
		'No errors.', // 0
		sprintf('Quote %s not found.', $param[0]), // 1
		'Quote database is empty', // 2
		'Bad request.', // 3
		'Internal error.' // 4
	);

	$result = Array (
		'error' => 1,
		'errorcode' => $errorcode,
		'errormsg' => $errormsg[$errorcode]
	);
	send_result($result);
}

function send_result($array)
{
	header('Content-type: application/json');
	echo json_encode($array);
	die;
}

function utf8_encode_all($dat) // -- It returns $dat encoded to UTF8
{
	if (is_string($dat)) return utf8_encode($dat);
	if (!is_array($dat)) return $dat;
	$ret = array();
	foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
	return $ret;
} 

?>